<!-- p_purchase.ftl 采购单 -->
var PPurchase = {
    u: '/pPurchase'
    , uList: '/pPurchase/list'
    , uEdit: '/pPurchase/edit'
    , uDel: '/pPurchase/delete'
    , uDetail: '/pPurchase/detail'
    , typeArr: []
    ,unitArr: []
};
// 处理按钮
PPurchase.btn = function () {
    var sb = new $yd.SearchBtn($(PPurchase.obtn));
    sb.create('cut green', '整单退货', PPurchase.allReturn);
    sb.create('repeat red', '重置', PPurchase.reset);
    sb.create('print green', '打印', PPurchase.print);
    sb.create('remove', '删除', PPurchase.remove);
    // sb.create('refresh', '刷新', PPurchase.refresh);
    // sb.create('edit', '编辑', PPurchase.edit);
    sb.create('plus', '新增', PPurchase.plus);
    // sb.create('search', '查询', PPurchase.search);
};
PPurchase.printBtn = function () {
    var pb = new $yd.SearchBtn($(PPurchase.pbtn));
    pb.create('barcode green', '打印条码', PPurchase.printBarCode);
};

PPurchase.dg = function () {
    $.ajax({
        type: "POST",
        url: "/sysDict/purchase_type",
        dataType: "json",
        success: function (data) {
            PPurchase.typeArr = data;
        }
    });

    var grid = new $yd.DataGrid(PPurchase.dtable);
    grid.onDblClickRow = function (index, row) {
        // PPurchase.detail(row['id']); // 双击打开详情
        PPurchase.windowDetail(row['id']); // 双击打开详情
    };
    grid.rownumbers = true;
    grid.checkOnSelect = false; // 选择行不选中复选框
    grid.url = PPurchase.uList;
    grid.fitColumns = true;
    grid.singleSelect = true;
    grid.onClickRow = function (index,row) {

        $(this).datagrid('unselectRow', index);

        PPurchase.printTable.datagrid("reload", {
            purchaseId: row.id,

        });

    };
    grid.columns = [[
        {field: 'id', checkbox: true}
        , {field: 'code', title: '单号', width: 100,halign:'center',align:'center'}
        , {
            field: 'ptime', title: '采购日期', width: 80,halign:'center',align:'center', formatter: function (value) {
                return $yd.isEmpty(value) ? "" : value.substr(0, 10);
            }
        }
        , {
            field: 'ptype', title: '采购类型', width: 50,halign:'center',align:'center', formatter: function (value, row, index) {
                for (var i = 0; i < PPurchase.typeArr.length; i++) {
                    if (value == PPurchase.typeArr[i].value) {
                        return PPurchase.typeArr[i].text;
                    }
                }
                return value;
            }
        }
        , {
            field: 'goodsName', title: '商品摘要', width: 160,halign:'center',align:'center', formatter: function (value) {
                return PPurchase.formatDetail(value);
            }
        }
        , {field: 'relativeName', title: '供应商', width: 80,halign:'center',align:'center'}
        , {field: 'totalNum', title: '商品数', width: 80,halign:'center',align:'center'}
        , {field: 'amountActual', title: '应付总额', width: 50,halign:'center',align:'center', formatter: function (value, row, index) {
                return Number(value).toFixed(2);
            }}
        // , {field: 'amountAlready', title: '应付总额', hidden: true}
        , {
            field: 'payStatus', title: '结算状态', width: 50,halign:'center',align:'center', formatter: function (value) {
                if (value == 0) {
                    return '<label class="label label-success">未结清</label>';
                } else {
                    return '<label class="label label-default">已结清</label>';
                }
            }
        }
        , {
            field: 'orderStatus', title: '采购单状态', width: 50,halign:'center',align:'center', formatter: function (value) {
                if (value == 0) {
                    return '<label class="label label-success">待入库</label>';
                } else if(value == 1){
                    return '<label class="label label-default">已入库</label>';
                }else if(value == 3){
                    return '<label class="label label-primary">已退货</label>';
                }
            }
        }
        , {field: 'amountAlready', title: '已付总金额', width: 50,halign:'center',align:'center', formatter: function (value, row, index) {
                return Number(value).toFixed(2);
            }}
        , {field: 'username', title: '操作人', width: 50,halign:'center',align:'center'}
        // , {field: 'remark', title: '备注', width: 80}
        // , {field: 'ctime', title: '创建时间', width: 80}
    ]],

    grid.loadGrid();
};
PPurchase.relativeTable = function () {
    $.ajax({
        type: "POST",
        url: "/sysDict/materiel_MU",
        dataType: "json",
        success: function (data) {
            PPurchase.unitArr = data;
        }
    });
    // MMaterielTticar.relativeTable = $("#relativeGoods_table");
    var grid = new $yd.DataGrid(PPurchase.printTable);
    grid.url ='/pPurchase/detailList';
    grid.rownumbers = true;
    grid.singleSelect = true;
    grid.columns = [[
        {field: 'id', checkbox: true},//detailId
        {field: 'purchaseId', hidden: true},//采购单id
        {field: 'wearhouseId', hidden: true},//仓库
        {field: 'positionId', hidden: true},//库位
        {field: 'skusId', checkbox: false, hidden: true},//规格id
        {field: 'goodsName', title: '商品名称', width: 220},
        {field: 'goodsId', title: '商品ID', width: 80, hidden: true},
        {field: 'skus', title: '规格', width: 220},
        {field: 'code', title: '商品编号', width: 80},
        {field: 'barCode', title: '商品条码号', width: 120},
        {
            field: 'unit', title: '单位', width: 50, formatter: function (value, row, index) {
            for (var i = 0; i < PPurchase.unitArr.length; i++) {
                if (value == PPurchase.unitArr[i].id) {
                    return PPurchase.unitArr[i].text;
                }
            }
            return value;
        }
        },
        // {
        //     field: 'house',
        //     title: '仓库/库位',
        //     width: 200,
        //     formatter: function (value, row, index) {
        //         if ($yd.isEmpty(value)) {
        //             return "";
        //         }
        //         var arr = value.split("_");
        //         return arr[3] + "：" + arr[1];
        //     }
        // },
        {field: 'wearhouseName', title: '仓库', width: 90},
        // {field: 'batchCode', title: '批号', width: 90},
        {field: 'amount', title: '参考进价', width: 50},
        {
            field: 'amountActual',
            title: '实际进价',
            width: 50
        },
        {
            field: 'count',
            title: '数量',
            width: 50
        },
        {
            field: 'shouldPay', title: '总额', width: 50, formatter: function (value, row, index) {
            return Number(row.count) * Number(row.amountActual);
        }
        }
    ]]
    grid.loadGrid();
}
PPurchase.printBarCode = function (){
    var sels = PPurchase.printTable.datagrid('getSelections');
    if (!sels || sels.length < 1) {
        $yd.alert('请选中记录');
        return;
    }
    // console.log(sels);
    parent.inv.OpenPage("/pPurchase/printBarCode?wearhouseName=" + sels[0].wearhouseName+"&positionName="+sels[0].positionName+"&goodsName="+sels[0].goodsName+"&skus="+sels[0].skus+"&barCode="+sels[0].barCode, "<i class=\"menu-icon fa fa-flag\"></i>\n" +
        "<span class=\"menu-text\"> 打印条码</span>\n" +
        "<b class=\"arrow \"></b>", true);
    
    // var img =
    //     '<div class="col-sm-4">'
    //     + '<img src="/pPurchase/purchaseBarcode?barCode=' + sels[0].barCode
    //     + '"></div>';
    // $("#pbarcode").append(img);
}

PPurchase.formatDetail = function (value) {
    if ($yd.isEmpty(value)) {
        return "";
    }
    var result = "";
    var first = "";
    var arr = value.split(",");
    if (arr.length == 1) {
        return "<a style='color:blue' title='" + value + "'>" + value + "</a>";
    }
    for (var i = 0; i < arr.length; i++) {
        result += arr[i] + "\n";
        if (i == 0) {
            first = result;
        }
    }
    var html = "<a style='color:blue' title='" + result + "'>" + first + "..." + "</a>";

    return html;
};
PPurchase.dg.getOne = function () {
    var sels = PPurchase.dg.getSels();
    if (sels.length === 1) {
        return sels[0];
    }
    return null;
};
PPurchase.dg.getSels = function () {
    return PPurchase.dtable.datagrid('getChecked');
};

PPurchase.windowDetail = function (purchaseId) {
    var dg = $yd.win3.create('采购单详情', "/pPurchase/detailPage?purchaseId=" + purchaseId);
    // var dg = $yd.win3.create('采购单详情', "/pPurchase/detailPage?purchaseId=192271345211506688");
    dg.width = "70%";
    dg.height = "80%";
    dg.open(function (that, $win) {

    });
};

//整单退货
PPurchase.allReturn = function () {

    var sels = PPurchase.dg.getSels();
    if (sels.length != 1) {
        $yd.alert('请选择一条记录');
        return;
    }

    var ids = [];
    for (var i = 0; i < sels.length; i++) {
        var n = sels[i];
        if (n.orderStatus == 0) {
            $yd.alert('未入库无需整单退货');
            return;
        }
        if (n.orderStatus == 3) {
            $yd.alert('此单已退货，不能重复退货');
            return;
        }
        ids.push(n['id']);
    }

    $yd.confirm("确定对此单进行整单退货吗？",function () {
        var ids = [];
        $.each(sels, function (i, n) {
            ids.push(n['id']);
        });
        $yd.post("/purchaseReturn/allReturn", {id: ids}, function (data) {
            $yd.alert("生成退货单成功",function () {
                parent.inv.OpenPage("/purchaseReturn?searchText="+data , "<i class=\"menu-icon fa fa-flag\"></i>\n" +
                    "<span class=\"menu-text\">采购退货</span>\n" +
                    "<b class=\"arrow \"></b>", true)
            })

        });
    })
};

//删除
PPurchase.remove = function () {

    var sels = PPurchase.dg.getSels();
    if (sels.length == 0) {
        $yd.alert('请选择记录');
        return;
    }

    var ids = [];
    for (var i = 0; i < sels.length; i++) {
        var n = sels[i];
        if (n.orderStatus == 1) {
            $yd.alert('已入库不能删除');
            return;
        }
        if (n.orderStatus == 3) {
            $yd.alert('已退货不能删除');
            return;
        }
        if (n.payStatus == 1) {
            $yd.alert('已支付不能删除');
            return;
        }
        if (Number(n.amountAlready) != 0) {
            $yd.alert('已支付不能删除');
            return;
        }
        ids.push(n['id']);
    }

    $yd.confirm(function () {
        var ids = [];
        $.each(sels, function (i, n) {
            ids.push(n['id']);
        });
        $yd.post(PPurchase.uDel, {ids: ids}, function () {
            PPurchase.search();
        });
    })
};

// 重置
PPurchase.reset = function () {
    $("form.search-form").form('clear');
    PPurchase.search();
}
//
PPurchase.edit = function () {
    var sel = PPurchase.dg.getOne();
    if (!sel) {
        $yd.alert('请选择一条记录');
        return;
    }
    PPurchase._edit(sel['id'])
};
// 表单预处理
PPurchase.preForm = function () {
    new $yd.combobox("relativeId").load("/wRelativeUnit/list");
};
PPurchase._edit = function (id) {
    $yd.win.create('编辑采购单', PPurchase.uEdit + '?id=' + id).open(function (that, $win) {
            PPurchase.preForm();
            $yd.get(PPurchase.u + "/" + id, function (data) {
                $win.find('form').form('load', data);
            })
        }, function (that, $win) {
            $yd.form.create($win.find('form')).url(PPurchase.u).submit(function () {
                that.close();
                PPurchase.refresh();
            });
        }
    );
};
// 详情
PPurchase.detail = function (purchaseId) {
    parent.inv.OpenPage("/pPurchase/detail?purchaseId=" + purchaseId, "<i class=\"menu-icon fa fa-flag\"></i>\n" +
        "<span class=\"menu-text\"> 采购单详情</span>\n" +
        "<b class=\"arrow \"></b>", true)
}

PPurchase.print = function () {
    var sel = PPurchase.dg.getOne();
    if (!sel) {
        $yd.alert('请选择一条记录');
        return;
    }
    PPurchase._print(sel['id'])
};
//打印
PPurchase._print = function (purchaseId) {
    parent.inv.OpenPage("/pPurchase/print?purchaseId=" + purchaseId, "<i class=\"menu-icon fa fa-flag\"></i>\n" +
        "<span class=\"menu-text\"> 打印采购单</span>\n" +
        "<b class=\"arrow \"></b>", true)
}
//新增
PPurchase.plus = function () {
    parent.inv.OpenPage("/pPurchase/addPurchase",
        "<i class=\"menu-icon fa fa-flag\"></i>\n" +
        "<span class=\"menu-text\"> 新增采购单 </span>\n" +
        "<b class=\"arrow \"></b>", true)
};
//
PPurchase.refresh = function () {
    window.location.reload();
};
//搜索
PPurchase.search = function () {
    PPurchase.dtable.datagrid('load', PPurchase.sform.serializeObject());
};

$(function () {
    PPurchase.sform = $('#pPurchase_form');
    PPurchase.dtable = $('#pPurchase_table');
    PPurchase.printTable = $('#purchasePrint_table');
    PPurchase.obtn = '#pPurchase_btn';
    PPurchase.pbtn = '#printBtn';
    new $yd.combotreegrid("#relativeId").addCol("name", "名称").load("/wRelativeUnit/list?rproperty=2&status=0");

    PPurchase.dg(); // 数据表格
    PPurchase.btn(); // 初始化按钮
    PPurchase.printBtn();//打印条码按钮
    PPurchase.relativeTable();
    $yd.bindEnter(PPurchase.search);
    $("#searchButton").click(PPurchase.search);

    if(!$yd.isEmpty($("#hidRelativeId").val())) {
        $("#relativeId").combotreegrid("setValue", {id:$("#hidRelativeId").val(), name:$("#hidRelativeName").val()});
        $("#startTime").datebox("setValue", $("#hidStartTime").val());
        $("#endTime").datebox("setValue", $("#hidEndTime").val());
        setTimeout("PPurchase.search()", 100);
    }
    if(!$yd.isEmpty($("#hidSearchText").val())) {
        $("#searchText").textbox("setValue", $("#hidSearchText").val());
        $("#startTime").datebox("setValue", $("#hidStartTime").val());
        $("#endTime").datebox("setValue", $("#hidEndTime").val());
        setTimeout("PPurchase.search()", 100);
    }

    $("input[name='payStatus']").combobox({
        url: "/sysDict/sales_pay_status",
        panelHeight: 'auto',
        valueField: 'id',
        textField: 'text',
        editable: false,
    });

    $("input[name='orderStatus']").combobox({
        url: "/sysDict/purchase_order_status",
        panelHeight: 'auto',
        valueField: 'id',
        textField: 'text',
        editable: false,
    });
});

// function doPrint() {
//     console.log(11111)
//     $('#printArea').panel({
//         closed: false,
//         href: '/pPurchase/print',
//         onLoad: function () {// 加载成功 （将请求url成功后返回的打印内容载入到这个panel中）
//             console.log(2222)
//             $("#printArea").jqprint(); // 打印内容
//         },
//         onLoadError: function () {// 加载失败
//             console.log(33333)
//             $.messager.alert('错误消息', '连接打印机失败请稍后重试', 'error');
//         }
//     });
//     // $('#printArea').panel('close');// 关闭打印区域
// };